import type { HttpResponsePending } from '@/server/interface'
import type { AxiosResponse } from 'axios'
import type { SiteData } from '@/stores/modules/site/interface'
import type { LoginRes } from '@/pages/login/api/interface'
import type * as I from './interface'
import type { RoleEnum } from '@/role'

import { getServerBaseURL } from '@/config'
import { http } from '@/server'
import { SITE_DOMAIN } from '@/stores/modules/site/constant'

/**
 * 刷新 token
 * @returns
 */
export const refreshToken = (): HttpResponsePending<I.RefreshToken.Res> =>
    http.post('/oauth/refresh-token')

/** 获取站点信息 */
export const fetchSiteInfo = (): HttpResponsePending<SiteData> => {
    const headers = { 'X-Site-Domain': SITE_DOMAIN[BUILD_ENV].country }
    return http.get('/oauth/website', { headers })
}

/**
 * 获取字典数据
 * @param type
 * @returns
 */
export const fetchDict = (type: I.Dictionary.Type): HttpResponsePending<I.Dictionary.Res> =>
    http.get('/books', { params: { code: type } })

/** 切换角色 */
export const switchRole = (uid: number, roleId: RoleEnum): HttpResponsePending<LoginRes> =>
    http.post(`/engineer/system/switch-role/${roleId}`)

/**
 * 获取字典数据列表
 */
export const fetchDictList = (typeList: I.Dictionary.Type[]): Promise<I.Dictionary.Res[]> => {
    const dictListPending = typeList.map(async type => {
        // 调用了多个接口，可能会有几个没有调用成功。
        // 返回空对象防止报错
        try {
            const { data } = await fetchDict(type)
            return data
        } catch (error) {
            console.error(error)
            return {}
        }
    })
    const dictList = Promise.all(dictListPending)

    return dictList
}

/**
 * 上传文件
 * @param data
 * @returns
 */
export const upload = (data: I.Upload.Body): HttpResponsePending<I.Upload.Res> => {
    const { type = 0 } = data

    return http
        .post<any, AxiosResponse<I.Upload.Res>>(
            '/resource/attachment-upload',
            { type, ...data },
            {
                headers: {
                    'Content-Type': 'multipart/form-data',
                },
            },
        )
        .then(res => {
            // 自动凭借接口前缀
            if (res.data.url.indexOf('http') === -1) {
                res.data.url = getServerBaseURL(false) + '/storage/' + res.data.url
            }

            return (res as unknown) as HttpResponsePending<I.Upload.Res>
        })
}
